package com.psm.model;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.psm.util.MD5;

import java.util.List;


/**
 * Created by cheam on 15/6/19.
 */
public class SysRole extends Model<SysRole> {

    public static String tableName="sys_role";

    public static final SysRole me = new SysRole();


    /**
     * 所有 sql 与业务逻辑写在 Model 或 Service 中，不要写在 Controller 中，养成好习惯，有利于大型项目的开发与维护
     */
    public Page<SysRole> pageinate(int pageNumber, int pageSize,String keyword,String year) {

        return paginate(pageNumber, pageSize,"select * ", "from "+tableName );
    }

    public List<Record> getUserRole(String token){
        return  Db.find("select r.id,r.name,ifnull(rr.id,0) checked from sys_role r left join (select * from sys_ref_user_role rr where rr.sys_user_id=" + token + ") rr on rr.sys_role_id =r.id ");
    }
    public List<Record> getUserRoleForOtherAdmin(String token){
        return  Db.find("select r.id,r.name,ifnull(rr.id,0) checked from sys_role r left join (select * from sys_ref_user_role rr where rr.sys_user_id=" + token + ") rr on rr.sys_role_id =r.id where r.id not in(1,3,4) ");
    }

    public List<Record> getRoleForUser(String token){
        return  Db.find("select * from sys_ref_user_role rr where rr.sys_role_id in (1,3,4) and rr.sys_user_id=" + token );

    }

    public List<Record> load_resource(String role_id){
        return Db.find("select r.id,r.parent_id pId,r.name,(case when rr.sys_role_id is null then 'false' else 'true' end ) checked,'true' as open from sys_resource r left join sys_ref_role_resource rr on rr.sys_resource_id= r.id and rr.sys_role_id=" +role_id+ "  order by r.parent_id ");
    }

    public boolean is_teacher(String token){
        List<Record> lr =  Db.find("select * from sys_ref_user_role rr where rr.sys_role_id in (5,8) and rr.sys_user_id=" + token );
        if(lr.size()>0){
            return true;
        }else{
            return false;
        }
    }
    public boolean is_admin(String token){
        List<Record> lr =  Db.find("select * from sys_ref_user_role rr where rr.sys_role_id in (1,3,4,6,7) and rr.sys_user_id=" + token );
        if(lr.size()>0){
            return true;
        }else{
            return false;
        }
    }
}
